//
//  YLCNetWorking.m
//  LinYa
//
//  Created by 初程程 on 2018/3/4.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCNetWorking.h"
#import "AFNetworking.h"
#import "YLCLoginManager.h"
@implementation YLCNetWorking
+ (AFHTTPSessionManager *)afnManager{
    
    AFHTTPSessionManager *httpRequest = [AFHTTPSessionManager manager];
    
    httpRequest.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    AFHTTPRequestSerializer *request = [AFHTTPRequestSerializer serializer];
    
    httpRequest.requestSerializer = request;
    
    httpRequest.requestSerializer.timeoutInterval =  10;
    
    return httpRequest;
}
+ (NSString *)allUrlPathWithPath:(NSString *)path
{
    return [NSString stringWithFormat:@"%@%@",BASE_URL,path];
}
+ (void)loadNetServiceWithParam:(id)param
                         method:(NSString *)method
                        urlPath:(NSString *)urlPath
                       delegate:(id)delegate
                       response:(void (^)(id responseObject ,NSError *error))responseBlock{
    [SVProgressHUD show];
    NSString *path = [self allUrlPathWithPath:urlPath];
    NSLog(@"【请求链接】%@",path);
    NSLog(@"【请求体：】%@",param);
    AFHTTPSessionManager *manager = [self afnManager];
    
    [manager POST:path parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self catchNetResWithResInfo:responseObject response:responseBlock delegate:delegate path:urlPath];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self catchErrorWithError:error response:responseBlock delegate:delegate];
    }];
}
+ (void)loadThireNetServiceWithParam:(id)param
                              method:(NSString *)method
                             urlPath:(NSString *)urlPath
                            delegate:(id)delegate
                            response:(void (^)(id responseObject ,NSError *error))responseBlock{
    [SVProgressHUD show];
    NSLog(@"【请求链接】%@",urlPath);
    NSLog(@"【请求体：】%@",param);
    AFHTTPSessionManager *manager = [self afnManager];
    
    [manager POST:urlPath parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self catchThirdNetResWithResInfo:responseObject response:responseBlock delegate:delegate path:urlPath];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self catchErrorWithError:error response:responseBlock delegate:delegate];
    }];
}
+ (void)uploadImageWithParam:(id)param
                   imageList:(NSArray *)imgList
                    fileName:(NSString *)fileName
                      method:(NSString *)method
                     urlPath:(NSString *)urlPath
                    delegate:(id)delegate
                    response:(void (^)(id responseObject ,NSError *error))responseBlock{
    
    [SVProgressHUD show];
    NSString *path = [self allUrlPathWithPath:urlPath];
    NSLog(@"【请求链接】%@",path);
    NSLog(@"【请求体：】%@",param);
    AFHTTPSessionManager *manager = [self afnManager];
    
    [manager POST:path parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        int i = 0;
        for (UIImage *headImage in imgList) {
            if (headImage) {
                i++;
                UIImage *newImage = [headImage  ccc_resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(headImage.size.width/3, headImage.size.height/3) interpolationQuality:kCGInterpolationDefault];
                
                NSData *data = UIImagePNGRepresentation(newImage);
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                
                formatter.dateFormat = @"yyyyMMddHHmmss";
                
                NSString *str = [formatter stringFromDate:[NSDate date]];
                
                NSString *datefileName = [NSString stringWithFormat:@"%@%d.%@", str,i,@"png"];
                
                [formData appendPartWithFileData:data name:fileName fileName:datefileName mimeType:@"jpeg"];
                
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self catchNetResWithResInfo:responseObject response:responseBlock delegate:delegate path:path];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self catchErrorWithError:error response:responseBlock delegate:delegate];
    }];

    
}
+ (void)catchThirdNetResWithResInfo:(id )info
                           response:(void (^)(id responseObject ,NSError *error))response
                           delegate:(UIViewController *) delegate
                               path:(NSString *)path{
    [SVProgressHUD dismiss];
    NSDictionary *dic = (NSDictionary *)[info objectFromJSONData];
    NSLog(@"%@",dic);
    if (dic) {
        response(dic,nil);
    }
}
+ (void)catchNetResWithResInfo:(id )info
                     response:(void (^)(id responseObject ,NSError *error))response
                     delegate:(UIViewController *) delegate
                         path:(NSString *)path{
    [SVProgressHUD dismiss];
    NSDictionary *dic = (NSDictionary *)[info objectFromJSONData];
    
    NSLog(@"%@",dic);
    
    NSString *message = dic[@"msg"];
    
    if (JK_IS_DICT_NIL(dic)) {
        NSString *string = [[ NSString alloc] initWithData:info encoding:NSUTF8StringEncoding];
        NSLog(@"===%@",string);
    }
    
    NSLog(@"【message】%@",message);
    
    NSString *code = dic[@"status"];
    
    NSDictionary *dataDic = @{};
    
    if ([dic.allKeys containsObject:@"data"]) {
        dataDic = dic[@"data"];
    }
    NSError *netError = [NSError errorWithDomain:@"NetWorkingError" code:100 userInfo:@{@"path":path}];
    
    NSError *resumeError = [NSError errorWithDomain:@"ResumeNetWorkingError" code:1001 userInfo:@{@"path":path}];

    switch ([code integerValue]) {
        case 200:
            response(dataDic,nil);
            break;
        case 10001:
            response(nil ,netError);
            [YLCLoginManager showLoginViewWithTarget:delegate];
            break;
        case 10002:
            response(nil ,netError);
            [YLCLoginManager showLoginViewWithTarget:delegate];
            break;
        case 10004:
            response(nil ,netError);
            [YLCLoginManager showLoginViewWithTarget:delegate];
            break;
        case 1001:
            response(nil ,resumeError);
            [SVProgressHUD showErrorWithStatus:message];
            break;
        default:
            response(nil ,netError);
            [SVProgressHUD showErrorWithStatus:message];
            break;
    }
    
//    NSDictionary *failDic = @{@"code":code,@"message":message};
    
}
+ (void)catchErrorWithError:(NSError *)error
                  response:(void (^)(id responseObject ,NSError *error))response
                  delegate:(id)delegate{
    [SVProgressHUD dismiss];
    NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
    NSString *errorStr = [[ NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"----%@----",errorStr);
    
    
}
@end
